package com.csc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @description:
 * @author: ChenShuCheng
 * @create: 2021-06-07 20:41
 **/
public class NettyServer {


    public void bind(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();


        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChildChannelHandler());
            ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline pipeline = socketChannel.pipeline();
            //todo 解码协议
//            pipeline.addLast();
            //todo 粘包拆包编码器
//            pipeline.addLast();
            //todo 转码协议
//            pipeline.addLast();
            //todo 心跳机制
//            pipeline.addLast();
            //todo 服务端核心处理
            pipeline.addLast(new MiniMQServerHandler());
        }
    }

    public static void main(String[] args) {
        NettyServer server = new NettyServer();
        server.bind(8989);
    }
}
